package com.ren.service.oss.service.impl;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.ren.service.oss.config.OssProperties;
import com.ren.service.oss.service.IOssFileService;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author RenGaoshuai
 * @date 2023/8/8 9:30
 * @description
 */
@Service
public class OssFileServiceImpl implements IOssFileService {


    @Override
    public String upload(InputStream inputStream, String module, String fileName) {

        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);

        //判断示例是否存在
        if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)) {
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }

        //文件路径
        String folder = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        //文件名：uuid.扩展名
        fileName = IdUtil.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        //文件根路径
        String key = module + "/" + folder + "/" + fileName;

        //上传
        ossClient.putObject(OssProperties.BUCKET_NAME,key,inputStream);

        //关闭oss
        ossClient.shutdown();

        //阿里云文件绝对路径
        return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + key;

    }
}
